
package com.classroompie.classroompieserver.controller;

import com.classroompie.classroompiecommon.constant.ErrorConstant;
import com.classroompie.classroompiecommon.exception.FileException;
import com.classroompie.classroompiecommon.result.Result;
import com.classroompie.classroompiecommon.utils.FileUtil;
import com.classroompie.classroompiecommon.utils.UUIDUtil;
import com.classroompie.classroompiepojo.request.BatchFileRequest;
import com.classroompie.classroompiepojo.request.FileRequest;
import com.classroompie.classroompiepojo.response.FileResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/file")
@Slf4j
@CrossOrigin("*")
public class FileController {

    @RequestMapping(value = {"/upload"}, method = RequestMethod.POST)
    public Result<FileResponse> upload(@ModelAttribute FileRequest request) {
        String id = UUIDUtil.UUID();
        if (request.getFile().isEmpty() || StringUtils.isEmpty(request.getFilePath())) {
            throw new FileException(ErrorConstant.PARAMS_ERROR);
        }

        return Result.success(FileUtil.upload(request.getFile(), request.getFilePath(), id));
    }

    @RequestMapping(value = {"/batchUpload"}, method = RequestMethod.POST)
    public Result<List<FileResponse>> batchUpload(@ModelAttribute BatchFileRequest request) {
        if (StringUtils.isEmpty(request.getFilePath()) || request.getFiles().length == 0) {
            throw new FileException(ErrorConstant.PARAMS_ERROR);
        }

        return Result.success(FileUtil.batchUpload(request.getFiles(), request.getFilePath()));
    }

    @PostMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestBody Map<String, String> fileInfo) {
        String filePath = FileUtil.rootFilePath + "//" + fileInfo.get("fileInfo");
        try {
            // 根据传入的文件路径创建文件对象
            Path path = Paths.get(filePath);
            File file = path.toFile();

            if (!file.exists()) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }

            // 创建文件资源
            FileSystemResource resource = new FileSystemResource(file);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
            headers.add(HttpHeaders.CONTENT_TYPE, "application/octet-stream");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    @RequestMapping(value = {"/delete"}, method = RequestMethod.DELETE)
    public Result<Boolean> delete(@RequestBody String[] paths) {
        /*
         * paths表示要删除文件的相对路径，不可为空
         * 可进行单个文件删除，也可批量删除
         * */
        if (paths == null || paths.length == 0) {
            throw new FileException(ErrorConstant.PARAMS_ERROR);
        }

        return Result.success(FileUtil.delete(paths));
    }
}
